<template>
  <CollapseContainer
    :title="t('routes.dashboard.account.setting.accountBind.title')"
    :canExpand="false"
  >
    <List>
      <ListItem v-if="oAuth2InfoRef.WeChat">
        <template #actions>
          <a v-if="formData.Wechat">
            <Button type="link" size="small" @click="handleUnbind('WeChat')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleBind('WeChat')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #avatar>
            <Icon class="avatar" icon="ri:wechat-fill" color="#54b738" />
          </template>
          <template #title>
            {{ t('routes.dashboard.account.setting.accountBind.wechatTitle') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.accountBind.accountBindDescription', [
                  t('routes.dashboard.account.setting.accountBind.wechatTitle'),
                  formData.Wechat?.DisplayName,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem v-if="oAuth2InfoRef.DingTalk">
        <template #actions>
          <a v-if="formData.DingTalk">
            <Button type="link" size="small" @click="handleUnbind('DingTalk')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleBind('DingTalk')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #avatar>
            <Icon class="avatar" icon="ant-design:dingding-outlined" color="#47a1f7" />
          </template>
          <template #title>
            {{ t('routes.dashboard.account.setting.accountBind.dingtalkTitle') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.accountBind.accountBindDescription', [
                  t('routes.dashboard.account.setting.accountBind.dingtalkTitle'),
                  formData.DingTalk?.DisplayName,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem v-if="oAuth2InfoRef.TikTok">
        <template #actions>
          <a v-if="formData.TikTok">
            <Button type="link" size="small" @click="handleUnbind('TikTok')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleBind('TikTok')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #avatar>
            <img class="avatar" width="40" :src="tiktokImg" />
          </template>
          <template #title>
            {{ t('routes.dashboard.account.setting.accountBind.tiktokTitle') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.accountBind.accountBindDescription', [
                  t('routes.dashboard.account.setting.accountBind.tiktokTitle'),
                  formData.TikTok?.DisplayName,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem v-if="oAuth2InfoRef.QQ">
        <template #actions>
          <a v-if="formData.QQ">
            <Button type="link" size="small" @click="handleUnbind('QQ')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleBind('QQ')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #avatar>
            <img class="avatar" width="40" :src="qqImg" />
          </template>
          <template #title>
            {{ t('routes.dashboard.account.setting.accountBind.qqTitle') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.accountBind.accountBindDescription', [
                  t('routes.dashboard.account.setting.accountBind.qqTitle'),
                  formData.QQ?.DisplayName,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem v-if="oAuth2InfoRef.Microsoft">
        <template #actions>
          <a v-if="formData.Microsoft">
            <Button type="link" size="small" @click="handleUnbind('Microsoft')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleBind('Microsoft')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #avatar>
            <Icon class="avatar" icon="grommet-icons:windows-legacy" />
          </template>
          <template #title>
            {{ t('routes.dashboard.account.setting.accountBind.microsoftTitle') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.accountBind.accountBindDescription', [
                  t('routes.dashboard.account.setting.accountBind.microsoftTitle'),
                  formData.Microsoft?.DisplayName,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem v-if="oAuth2InfoRef.GitHub">
        <template #actions>
          <a v-if="formData.GitHub">
            <Button type="link" size="small" @click="handleUnbind('GitHub')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleBind('GitHub')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #avatar>
            <Icon class="avatar" icon="logos-github-octocat" />
          </template>
          <template #title>
            {{ t('routes.dashboard.account.setting.accountBind.githubTitle') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.accountBind.accountBindDescription', [
                  t('routes.dashboard.account.setting.accountBind.githubTitle'),
                  formData.GitHub?.DisplayName,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
    </List>
  </CollapseContainer>
</template>
<script lang="ts" setup>
  import { List, Button } from 'ant-design-vue';
  import { onMounted, reactive, h, ref, watchEffect } from 'vue';
  import { CollapseContainer } from '@/components/Container/index';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import Icon from '@/components/Icon/Icon.vue';
  import { useLoading } from '@/components/Loading';

  import qqImg from '@/assets/images/qq_2x.png';
  import tiktokImg from '@/assets/images/tiktok_2x.png';

  import { getOAuth2Info } from '@/api/sys';
  import { readOAuth2, oAuth2Bind, removeOAuth2 } from '@/api/identity';
  import { UserLoginOutputDto } from '@/api/identity/model';
  import { PageRequest } from '@/utils/common/types';

  import { urlEncode } from '@/utils/common';

  /** 账户绑定数据 */
  interface AccountBindData {
    /** 微信 */
    Wechat?: UserLoginOutputDto;
    /** 钉钉 */
    DingTalk?: UserLoginOutputDto;
    /** 抖音 */
    TikTok?: UserLoginOutputDto;
    /** QQ */
    QQ?: UserLoginOutputDto;
    /** 微软 */
    Microsoft?: UserLoginOutputDto;
    /** GitHub */
    GitHub?: UserLoginOutputDto;
  }

  const ListItem = List.Item;
  const ListItemMeta = List.Item.Meta;

  const { t } = useI18n();
  const { createMessage, createConfirm } = useMessage();
  const [openLoading, closeLoading] = useLoading({});

  const formData: AccountBindData = reactive({});

  const oAuth2InfoRef = ref<any>({});

  watchEffect(async () => {
    oAuth2InfoRef.value = await getOAuth2Info();
  });

  onMounted(async () => {
    const pageRequest = new PageRequest();
    const pageData = await readOAuth2(pageRequest, 'none');
    if (pageData.Rows.length > 0) {
      for (let rowData of pageData.Rows) {
        const loginProvider = rowData.LoginProvider?.toLowerCase();
        switch (loginProvider) {
          case 'wechat':
            formData.Wechat = rowData;
            break;
          case 'dingtalk':
            formData.DingTalk = rowData;
            break;
          case 'tiktok':
            formData.TikTok = rowData;
            break;
          case 'qq':
            formData.QQ = rowData;
            break;
          case 'microsoft':
            formData.Microsoft = rowData;
            break;
          case 'github':
            formData.GitHub = rowData;
            break;
        }
      }
    }
  });

  /** 处理取消绑定 */
  async function handleUnbind(
    key: 'WeChat' | 'DingTalk' | 'TikTok' | 'QQ' | 'Microsoft' | 'GitHub',
  ) {
    try {
      openLoading();

      let confirmMessage = '';
      let oauth2Id = '0';
      switch (key) {
        case 'WeChat':
          confirmMessage = t('routes.dashboard.account.setting.confirmUnbindText', [
            formData.Wechat?.DisplayName,
          ]);
          if (formData.Wechat?.Id !== undefined && formData.Wechat?.Id !== null) {
            oauth2Id = formData.Wechat.Id.toString();
          }
          break;
        case 'DingTalk':
          confirmMessage = t('routes.dashboard.account.setting.confirmUnbindText', [
            formData.DingTalk?.DisplayName,
          ]);
          if (formData.DingTalk?.Id !== undefined && formData.DingTalk?.Id !== null) {
            oauth2Id = formData.DingTalk.Id.toString();
          }
          break;
        case 'TikTok':
          confirmMessage = t('routes.dashboard.account.setting.confirmUnbindText', [
            formData.TikTok?.DisplayName,
          ]);
          if (formData.TikTok?.Id !== undefined && formData.TikTok?.Id !== null) {
            oauth2Id = formData.TikTok.Id.toString();
          }
          break;
        case 'QQ':
          confirmMessage = t('routes.dashboard.account.setting.confirmUnbindText', [
            formData.QQ?.DisplayName,
          ]);
          if (formData.QQ?.Id !== undefined && formData.QQ?.Id !== null) {
            oauth2Id = formData.QQ.Id.toString();
          }
          break;
        case 'Microsoft':
          confirmMessage = t('routes.dashboard.account.setting.confirmUnbindText', [
            formData.Microsoft?.DisplayName,
          ]);
          if (formData.Microsoft?.Id !== undefined && formData.Microsoft?.Id !== null) {
            oauth2Id = formData.Microsoft.Id.toString();
          }
          break;
        case 'GitHub':
          confirmMessage = t('routes.dashboard.account.setting.confirmUnbindText', [
            formData.GitHub?.DisplayName,
          ]);
          if (formData.GitHub?.Id !== undefined && formData.GitHub?.Id !== null) {
            oauth2Id = formData.GitHub.Id.toString();
          }
          break;
      }
      if (oauth2Id && oauth2Id !== '' && oauth2Id !== '0') {
        createConfirm({
          zIndex: 999999999,
          iconType: 'warning',
          title: () => h('span', t('common.warmReminderText')),
          content: () => h('span', confirmMessage),
          onOk: async () => {
            const result = await removeOAuth2([oauth2Id]);
            if (result.Succeeded) {
              createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
            } else {
              createMessage.error(result.Content);
            }
          },
        });
      }
    } finally {
      closeLoading();
    }
  }

  /** 处理绑定 */
  async function handleBind(
    type: 'WeChat' | 'DingTalk' | 'TikTok' | 'QQ' | 'Microsoft' | 'GitHub',
  ) {
    const callback = `/#/dashboard/account/setting/${type}`;
    const urlParams = `provider=${type}&returnUrl=${urlEncode(callback)}`;
    oAuth2Bind(urlParams);
  }
</script>

<style lang="less" scoped>
  .avatar {
    font-size: 40px !important;
  }
</style>
